﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TypeWrite.MVC4.Areas.Setup.Models;

namespace TypeWrite.MVC4.Areas.Setup.Controllers
{
    public class DataSourceController : Controller
    {

        //
        // GET: /Setup/DataSource/Create

        public ActionResult Create()
        {
            return View(new DataSource());
        }

        //
        // SET: /Setup/DataSource/Create
        [HttpPost]
        public ActionResult Create(DataSource model)
        {
            if (model != null)
            {
                string connectionString = string.Format("Data Source={0};Database={1};User ID={2};Password={3};", model.Server, model.Database, model.UserID, model.Password);

                using (TypeWrite.Data.TypeWriteDataContext db = TypeWrite.Data.ContextFactory.CreateInstance(connectionString))
                {

                    if (!db.DatabaseExists())
                    {
                        db.CreateDatabase();
                    }

                    if (db.DatabaseExists())
                    {
                        Core.Settings.Instance.DbAdmin = model.UserID;
                        Core.Settings.Instance.DbInstance = model.Server;
                        Core.Settings.Instance.DbName = model.Database;
                        Core.Settings.Instance.DbPassword = model.Password;

                        Core.Settings.Instance.Save();

                        return RedirectToAction("Create", "AdminAccount", new { area = "Setup" });
                    }
                    else
                    {
                        return RedirectToAction("Create");
                    }

                }

            }

            return RedirectToAction("Create");
        }

    }
}
